from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse
from pyecharts.globals import ThemeType

from applications.common.render_template import templates
from applications.utils.chart.chart_utils import ChartUtils
from applications.utils.chart.chart_builders import (
    build_stacked_percent_bar,
    build_rose_pie,
    build_boxplot,
    build_bar3d_stack,
    build_map_china,
)

router = APIRouter(prefix="/chart", tags=["图表管理"])


@router.get("/", summary="获取雷达图数据", response_class=HTMLResponse)
async def get_base_chart(request: Request):
    # 你的示例数据
    x_axis = [1, 2, 3, 4, 5]
    a = [12, 23, 33, 3, 33]
    b = [3, 21, 5, 52, 43]

    bar_chart_obj = build_stacked_percent_bar(x_axis, a, b, title="stack_bar", theme=ThemeType.LIGHT)
    pie_chart_obj = build_rose_pie(title="玫瑰图", theme=ThemeType.LIGHT)

    line_chart_obj = ChartUtils.create_line_chart(
        title="温度变化",
        x_axis=["1日", "2日", "3日", "4日", "5日", "6日", "7日"],
        y_axis=[
            {"name": "最高温度", "data": [30, 32, 33, 29, 28, 31, 35]},
            {"name": "最低温度", "data": [20, 22, 23, 18, 17, 20, 22]},
        ],
        x_name="日期",
        y_name="温度(℃)",
        is_smooth=True,
    )

    box_chart_obj = build_boxplot(
        labels=["expr1", "expr2"],
        data_groups=[
            [
                [850, 740, 900, 1070, 930, 850, 950, 980, 980, 880, 1000, 980],
                [960, 940, 960, 940, 880, 800, 850, 880, 900, 840, 830, 790],
            ],
            [
                [890, 810, 810, 820, 800, 770, 760, 740, 750, 760, 910, 920],
                [890, 840, 780, 810, 760, 810, 790, 810, 820, 850, 870, 870],
            ],
        ],
        series_names=["A", "B"],
        title="BoxPlot-基本示例",
    )

    return templates.TemplateResponse(
        request=request,
        name="system/echarts/chart_test.html",
        context={
            # 保持和你之前一样的上下文键
            "radar_chart": bar_chart_obj.render_embed(),  # 原来叫 radar，但其实是 Bar，先不改名
            "bar_chart": pie_chart_obj.render_embed(),
            "line_chart": line_chart_obj.render_embed(),
            "boxplot_chart": box_chart_obj.render_embed(),
        },
    )


@router.get("/3d", summary="获取3D图表数据", response_class=HTMLResponse)
async def get_3d_chart(request: Request):
    bar3d_obj = build_bar3d_stack(x_data=range(10), y_data=range(10), stacks=10)
    return templates.TemplateResponse(
        request=request,
        name="system/echarts/chart_3d.html",
        context={
            "bar3d": bar3d_obj.render_embed(),
        },
    )


@router.get("/map", response_class=HTMLResponse)
async def chart_map(request: Request):
    map_obj = build_map_china()
    return templates.TemplateResponse(
        request=request,
        name="system/echarts/chart_map.html",
        context={
            "map_chart": map_obj.render_embed(),
        },
    )
